using System;
using System.Data;
using System.Collections;


namespace Handrise.Mobile.BasicModal.Serialization.Surrogate
{
    /// <summary>
    /// Summary description for DataTableOverrider.
    /// </summary>
    [Attributes.Overrider(typeof(System.Data.DataTable))]
    public class GhostDataTableOverrider : Interfaces.IOverrider
    {
        public GhostDataTableOverrider()
        { }

        #region ICFormatter Members

        public void Serialize(CompactFormatter parent, System.IO.Stream serializationStream, object graph)
        {
            ArrayList colNames = new ArrayList();
            ArrayList colTypes = new ArrayList();
            ArrayList dataRows = new ArrayList();

            DataTable dt = (DataTable)graph;
            foreach (DataColumn col in dt.Columns)
            {
                colNames.Add(col.ColumnName);
                colTypes.Add(col.DataType.FullName);
            }

            foreach (DataRow row in dt.Rows)
                dataRows.Add(row.ItemArray);

            // Now i've to serialize three ArrayList using the CompactFormatter main routines
            parent.Serialize(serializationStream, colNames);
            parent.Serialize(serializationStream, colTypes);
            parent.Serialize(serializationStream, dataRows);
        }

        public object Deserialize(CompactFormatter parent, System.IO.Stream serializationStream)
        {

            ArrayList colNames = (ArrayList)parent.Deserialize(serializationStream);
            ArrayList colTypes = (ArrayList)parent.Deserialize(serializationStream);
            ArrayList dataRows = (ArrayList)parent.Deserialize(serializationStream);

            DataTable dt = new DataTable();

            // Add columns
            for (int i = 0; i < colNames.Count; i++)
            {
                DataColumn col = new DataColumn(colNames[i].ToString(),
                    Type.GetType(colTypes[i].ToString()));
                dt.Columns.Add(col);
            }

            // Add rows
            for (int i = 0; i < dataRows.Count; i++)
            {
                DataRow row = dt.NewRow();
                row.ItemArray = (Object[])dataRows[i];
                dt.Rows.Add(row);
            }

            dt.AcceptChanges();
            return dt;
        }

        #endregion

        #region IOverrider Members


        public Type GetObjType()
        {
            return null;
        }

        #endregion
    }
}
